<template>
    <!-- 上架记录 -->
    <div class="p-2">
        <searchrevealing>
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="104px">
                <el-form-item label="商品名称" prop="styleName">
                    <el-input v-model="queryParams.styleName" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="上架时间" prop="outTime">
                    <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.outTime" type="daterange"
                        range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                        style="width: 220px" />
                </el-form-item>
                <el-form-item label="库存编码" prop="stockCode">
                    <el-input v-model="queryParams.stockCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>

                <el-form-item label="产品部门" prop="stockDeptId">
                    <el-select style="width: 220px" v-model="queryParams.stockDeptId" placeholder="请选择" clearable
                        filterable @change="productChange">
                        <el-option v-for="dict in productList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上架人" prop="stockUserId">
                    <el-select v-model="queryParams.stockUserId" placeholder="请选择" clearable style="width: 220px"
                        filterable>
                        <el-option v-for="dict in delistedPersonList" :key="dict.userId" :label="dict.nickName"
                            :value="dict.userId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品编码" prop="productsId">
                    <el-input v-model="queryParams.productsId" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" maxlength="19" />
                </el-form-item>
                <el-form-item label="69码" prop="styleCode">
                    <el-input v-model="queryParams.styleCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="货架号" prop="locationCode">
                    <el-input v-model="queryParams.locationCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="类目" prop="categoryIdList">
                    <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px" clearable
                        collapse-tags filterable ref="categoryRef" @change="handleChange" placeholder="请选择"
                        :props="props" />
                </el-form-item>


            </el-form>
            <div class="form_button">
                <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
            </div>
        </searchrevealing>
        <el-card shadow="never">
            <template #header>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'产品部上架记录'"
                    @updateColumn="getColmun"></right-toolbar>
            </template>
            <el-table v-loading="loading" :data="selectionRecordList" border @header-dragend="dragEnd">
                <el-table-column label="序号" type="index" width="55" align="center" :fixed="true" />
                <el-table-column v-for="(item, index) in listingRecordColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" :leftText="statisticsText" />
        </el-card>

    </div>
</template>



<script setup name="StorageRecord" lang="ts">
import { ListingQueryParmas, ListingRecordVO } from '@/api/group/productOutbound/types'
import { locationTree } from '@/api/depot/index'
import { listColumn } from '@/api/system/column';
import { getOffRecordList, getCategoryLists, getStickProductDept, getUserProductList } from '@/api/group/productOutbound/index'
const { proxy } = getCurrentInstance() as any;
const listingRecordColumns = ref()
const selectionRecordList = ref<ListingRecordVO[]>([]);
const loading = ref(true);
const total = ref(0);
const statisticsText = ref('')
const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();
const productList = ref<{ deptId: string; deptName: string; }[]>([])
const delistedPersonList = ref<{ userId: string; nickName: string; }[]>([])


const queryLoading = ref(false)
const columnData = ref()

const categoryRef = ref();
const locationCodeRef = ref()
const options = ref()
const props = {
    multiple: true
}

const queryParams = ref<ListingQueryParmas>({
    pageNum: 1,
    pageSize: 10,
    stockType: 1,
    categoryIds: undefined,
    categoryId: undefined,
    locationCode: undefined,
    styleName: undefined,
    stockDeptId: undefined,
    stockUserId: undefined,
    productsId: undefined,
    stockCode: undefined,
    styleCode: undefined,
    groundTime: undefined,
    outTime: [],
    outStartTime: '',
    outEndTime: '',
    categoryIdList: []
})

watch(() => queryParams.value.productsId, (newValue: any) => {
    if (isNaN(newValue) || newValue.length > 19) {
        queryParams.value.productsId = undefined;
    }
}, { deep: true })

/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
// 筛选库位change事件
const locationCodeChange = (val: [string, string, string, string]) => {
    if (val) {
        locationCodeRef.value.togglePopperVisible()
        queryParams.value.locationCode = val[val.length - 1]
    }
}
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {

}

/**
 * 获取产品部门信息
 */
const getProductList = async () => {
    const res = await getStickProductDept()
    productList.value = res.data
}

/**
 *  根据产品部获取下架人
 */
const productChange = async (event: string) => {
    if (event) {
        const res = await getUserProductList({ deptId: event })
        delistedPersonList.value = res.data
        queryParams.value.stockUserId = undefined
    } else {
        delistedPersonList.value = []
        queryParams.value.stockUserId = undefined
    }
}


/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        if (queryParams.value.outTime && queryParams.value.outTime.length) {
            queryParams.value.outStartTime = queryParams.value.outTime[0]
            queryParams.value.outEndTime = queryParams.value.outTime[1]
        } else {
            queryParams.value.outStartTime = ''
            queryParams.value.outEndTime = ''
        }
        const res = await getOffRecordList(queryParams.value);
        selectionRecordList.value = res.rows;
        total.value = res.total;
        statisticsText.value = res.msg
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.stockType = 1
    queryParams.value.categoryId = undefined
    delistedPersonList.value = []
    handleQuery();
};
/** 导出按钮操作 */
const handleExport = () => {
    proxy?.downloadAsync("basic/stock/getGroundExport", {
        ...queryParams.value,
    }, `上架记录_${new Date().getTime()}.xlsx`)
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('产品部上架记录')
    listingRecordColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
onMounted(async () => {
    queryParams.value.pageNum = 1;
    await getColmun();
    await getList();
    getCategoryList();
    getProductList();
})

</script>
<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}
</style>